import time
import atexit
import json

# with open("./file.txt", "r") as file:
#     money = dict(file.readline().strip())
#     password = dict(file.readline().strip())

money = {}
password = {}
prompt1 = """
[1] 办理银行卡
[2] 插入银行卡
[3] 退出

"""
prompt2 = """
[1] 取款
[2] 存款
[3] 查询金额
[4] 修改密码
[5] 退卡

"""


def save():
    with open("./ATMfile.txt", "w") as f:
        json.dump(money, f)
        json.dump(password, f)


# atexit.register(save)


def FormatCheck(variable, digits):
    while 1:
        if variable == "":
            variable = input("不能输入空白，请重新输入：")
            continue
        if variable.isdigit() == False:
            variable = input("格式不符合要求，请重新设置: ")
            continue
        if len(variable) != digits and variable != "0":
            variable = input("位数不符合要求，请重新设置: ")
            continue
        if variable == "0":
            print("已退出")
            return 1
        break


class ATM:
    # 注册
    def register():
        global money
        global password
        # 设置ID，设置密码，返回ID
        ID_pre = input("设置您的4位数字ID，退出请输入 0: ")
        if FormatCheck(ID_pre, 4) == 1:
            return -1
        if ID_pre == "0":
            return -1
        ID = int(ID_pre)
        pw_pre = input("设置你的6位数字密码: ")
        if FormatCheck(pw_pre, 6) == 1:
            return -1
        pw = int(pw_pre)
        money[ID] = 0
        password[ID] = pw
        print("注册成功")
        return ID

    # 登录
    def log_in():
        global money
        global password
        # 询问ID，验证密码，返回ID
        ID = int(input("请输入你的ID: "))
        try_times = 0
        try_times_rest = 3
        while ID == "":
            int(input("不能输入空白，请重新输入："))
        if ID in list(password.keys()) and ID != None:
            password_pre = int(input("请输入你的密码，退出请输入 0: "))
            while try_times <= 2 and password[ID] != password_pre and password_pre != 0:
                password_pre = int(
                    input(f"密码错误，请重新输入，您还有{try_times_rest}次机会：")
                )
                try_times += 1
                try_times_rest = 3 - try_times
            if password[ID] == password_pre:
                print("密码正确")
                return ID
            elif try_times > 2 and password[ID] != password_pre:
                print("\n密码尝试次数超出限制")
                return -2
            elif password_pre == 0:
                print("已退出")
                time.sleep(1)
                return -1
        else:
            print("\n您的ID不存在，请先注册")
            return -1

    # 取款
    def draw(ID):
        try_times = 0
        try_times_rest = 3
        global money
        global password
        password_pre = int(input("请输入密码："))
        if password[ID] == password_pre:
            print("密码正确")
        else:
            while try_times <= 2 and password[ID] != password_pre:
                password_pre = int(
                    input(f"密码错误，您还有{try_times_rest}次机会，请重新输入：")
                )
                try_times += 1
                try_times_rest = 3 - try_times
            if password[ID] == password_pre:
                print("密码正确")
            if try_times > 2 and password[ID] != password_pre:
                print("密码尝试次数超出限制")
                return -2
        value = int(input("请输入取款金额，退出请输入 0 : "))
        if value <= money[ID] and value != 0:
            money[ID] -= value
            print("\n交易正在处理，请稍后...")
            time.sleep(1)
            print(f"\n存款成功，当前余额为{money[ID]}")
            return money[ID]
        elif value == 0:
            return -1
        else:
            print("\n交易正在处理，请稍后...")
            time.sleep(1)
            print("\n您的余额不足\n")
            time.sleep(1)
            return -1

    # 存款
    def save(ID):
        global money
        global password
        value = int(input("请输入存款金额，退出请输入 0 : "))
        print("请放入钞票（等待）")
        time.sleep(3)
        print(f"\n您存款的金额为{value}")
        confirm = int(input("[1]确认  [2]取消\n\n"))
        if confirm == 1:
            money[ID] += value
            print("交易正在处理，请稍后...")
            time.sleep(1)
            print(f"\n存款成功，当前余额为{money[ID]}")
            return money[ID]
        if confirm == 2:
            print("请取走您的钞票")
            return -1


# 登录和注册
current_ID = None
choice1 = None
print("欢迎使用ATM")
while True:
    choice1 = input(prompt1)
    if choice1 == "1":
        current_ID_pre = ATM.register()
        if current_ID_pre == -1 or current_ID_pre == -2:
            current_ID = None
            continue
        else:
            current_ID = current_ID_pre
            break

    elif choice1 == "2":
        current_ID_pre = ATM.log_in()
        if current_ID_pre == -1 or current_ID_pre == -2:
            current_ID = None
            choice1 = None
            continue
        else:
            current_ID = current_ID_pre
            break
    elif choice1 == "3":
        print("\n期待下次为您服务！")
        choice2 = None
        exit()
    print("请重新输入")

# 选择服务项目
print(f"\n{current_ID}卡用户，请选择服务项目：")
choice2 = None
choice2 = input(prompt2)
while current_ID != None:
    while (
        choice2 != "1"
        and choice2 != "2"
        and choice2 != "3"
        and choice2 != "4"
        and choice2 != "5"
        and choice2 != None
    ):
        choice2 = input("请重新输入")
    if choice2 == None:
        choice2 = input(prompt2)

    # 存款和取款
    if choice2 == "1":
        draw = ATM.draw(current_ID)
        choice2 = None
        if draw == -2:
            choice2 = "5"
    elif choice2 == "2":
        ATM.save(current_ID)
        choice2 = None
    elif choice2 == "3":
        print("查询中...")
        time.sleep(1)
        print(f"\n您的余额为 {money[current_ID]} 元")
        time.sleep(1)
        choice2 = None
        continue
    elif choice2 == "4":
        try_times = 0
        try_times_rest = 3
        if_currect = True
        password_pre = int(input("请输入原密码："))
        if password[current_ID] == password_pre:
            print("密码正确")
            if_currect = True
        else:
            while password_pre == "":
                print("不能输入空白，请重新输入：")
            while try_times <= 2 and password[current_ID] != password_pre:
                password_pre = int(input("密码错误，请重新输入："))
                try_times += 1
                try_times_rest = 3 - try_times
            if password[current_ID] == password_pre:
                print("密码正确")
            if try_times > 2 and password[current_ID] != password_pre:
                print("密码尝试次数超出限制")
                choice2 = "5"
                if_currect = False
        while if_currect == True:
            password_new = input("请设置新密码（6位数字）：")
            FormatCheck(password_new, 6)
            while password_new == password[current_ID]:
                password_new = input("新旧密码不能相同，请重新设置: ")
            password_new1 = input("请再输入一次新密码：")
            if password_new == password_new1:
                password[current_ID] = int(password_new)
                print("密码修改成功")
                choice2 = None
                break
            else:
                print("两次输入不一致，请重新设置")
                time.sleep(1)

    # 退卡
    if choice2 == "5":
        # save()
        print("\n请取走您的卡片\n")
        time.sleep(1)
        current_ID = None
        choice2 = None
        while True:
            choice1 = input(prompt1)
            if choice1 == "1":
                current_ID_pre = ATM.register()
                if current_ID_pre == -1:
                    current_ID = None
                    continue
                else:
                    current_ID = current_ID_pre
                    break

            elif choice1 == "2":
                current_ID_pre = ATM.log_in()
                if current_ID_pre == -1:
                    current_ID = None
                    continue
                else:
                    current_ID = current_ID_pre
                    break
            elif choice1 == "3":
                print("\n期待下次为您服务！")
                exit()
            print("请重新输入")
            print(f"\n{current_ID}卡用户，请选择服务项目：")
            choice2 = input(prompt2)
            continue

print("\n期待下次为您服务！")
